package validator

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	"strings"
	"user_api/global"

	"github.com/go-playground/validator/v10"
)

//注册单独验证器的Demo
//func ValidateEmail(fl validator.FieldLevel) bool {
//	email := fl.Field().String()
//	//使用正则表达式判断是否合法
//	ok, _ := regexp.MatchString(`[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[a-zA-Z0-9]+`, email)
//	if !ok {
//		return false
//	}
//	return true
//}

func removeTopStruct(fileds map[string]string) map[string]string {
	rsp := map[string]string{}
	for field, err := range fileds {
		rsp[field[strings.Index(field, ".")+1:]] = err
	}
	return rsp
}

func HandleValidatorError(c *gin.Context, err error) {
	errs, ok := err.(validator.ValidationErrors)
	if !ok {
		zap.S().Debug("[HandleValidatorError] 校验参数异常: %s", err.Error())
		c.JSON(http.StatusMethodNotAllowed, gin.H{
			"code":    http.StatusMethodNotAllowed,
			"message": err.Error(),
		})
		return
	}
	c.JSON(http.StatusBadRequest, gin.H{
		"code":    http.StatusBadRequest,
		"message": removeTopStruct(errs.Translate(global.Trans)),
	})
	return
}
